package com.cg.design.graphicdesignpattern.flyweight;

import org.junit.Test;

/**
 * FlyWeight享元模式测试类
 *
 * @program: LeetCode->FlyWeightTest
 * @description: FlyWeight享元模式测试类
 * @author: cg
 * @create: 2022-04-03 16:43
 **/
public class FlyWeightTest {

    private static final BigString[] BIG_STRINGS_ARRAY = new BigString[1000];

    @Test
    public void testFlyWeight() {
        System.out.println("共享时：");
        testAllocation(true);
        System.out.println("非共享时：");
        testAllocation(false);
    }

    private static void testAllocation(boolean shared) {
        for (int i = 0; i < BIG_STRINGS_ARRAY.length; i++) {
            BIG_STRINGS_ARRAY[i] = new BigString("1212123-456", shared);
        }
        showMemory();
    }

    private static void showMemory() {
        Runtime.getRuntime().gc();
        long used = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
        System.out.println("使用内存 = " + used);
    }

}
